package events

import (
	"../golanghelper"
	"log"
	"sync"
)

var mapping map[string][]func()
var mutex sync.Mutex

func init() {
	mapping = make(map[string][]func())
}

func Register(event_name string, f func()) {
	mutex.Lock()
	defer mutex.Unlock()

	var list []func()
	list = mapping[event_name]

	list = append(list, f)
	mapping[event_name] = list
}

func Trigger(event_name string) {
	mutex.Lock()
	list := mapping[event_name]
	mutex.Unlock()

	if list != nil && len(list) > 0 {
		for _, f := range list {
			if err := golanghelper.SafeRun(f); err != nil {
				log.Println("Event.Trigger error", err.Error())
			}
		}
	}
}
